package com.jcrj.remoteclient.ui;

import net.tsz.afinal.annotation.view.ViewInject;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.jcrj.remoteclient.bean.CommandCode;
import com.jcrj.remoteclient.util.UIHelper;

public class MainActivity extends BaseActivity {

	@ViewInject(id = R.id.ServerNumSureBtn, click = "ServerNumSureBtnClick")
	Button ServerNumSureBtn;
	@ViewInject(id = R.id.ServerNumSetBtn, click = "ServerNumSetBtnClick")
	Button ServerNumSetBtn;
	@ViewInject(id = R.id.ServerNum)
	EditText ServerNum;

	@ViewInject(id = R.id.Cut1Btn)
	Button Cut1Btn;
	@ViewInject(id = R.id.Cut2Btn)
	Button Cut2Btn;
	@ViewInject(id = R.id.Cut3Btn)
	Button Cut3Btn;
	@ViewInject(id = R.id.Cut4Btn)
	Button Cut4Btn;
	@ViewInject(id = R.id.AllOpenBtn, click = "AllClick")
	Button AllOpenBtn;
	@ViewInject(id = R.id.AllCloseBtn, click = "AllClick")
	Button AllCloseBtn;

	@ViewInject(id = R.id.RemoteNum)
	EditText RemoteNum;
	@ViewInject(id = R.id.RemoteNumSureBtn, click = "RemoteNumSureBtnClick")
	Button RemoteNumSureBtn;

	@ViewInject(id = R.id.RemoteStateTxt)
	EditText RemoteStateTxt;
	@ViewInject(id = R.id.RemoteStateSearchBtn, click = "RemoteStateSearchBtnClick")
	Button RemoteStateSearchBtn;

	PendingIntent sentPI = null;
	PendingIntent deliverPI = null;
	String simNo = null;
	SmsManager smsManager = null;

	BroadcastReceiver sendReceiver = null;
	BroadcastReceiver getReceiver = null;
	BroadcastReceiver remoteReceiver = null;

	long now = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		Intent intent = getIntent();
		simNo = intent.getStringExtra("sim_card");
		smsManager = SmsManager.getDefault();
		iniListnr();
		iniReceiver();
		iniData();
	}

	private void iniListnr() {
		CutListener cutListnr = new CutListener();
		Cut1Btn.setOnTouchListener(cutListnr);
		Cut2Btn.setOnTouchListener(cutListnr);
		Cut3Btn.setOnTouchListener(cutListnr);
		Cut4Btn.setOnTouchListener(cutListnr);
	}

	private void iniReceiver() {
		sendReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context _context, Intent _intent) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					// UIHelper.ToastMessage(context, "短信发送成功");
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					UIHelper.ToastMessage(context, "操作失败");
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					UIHelper.ToastMessage(context, "操作失败");
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					UIHelper.ToastMessage(context, "操作失败");
					break;
				}
			}
		};

		getReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context _context, Intent _intent) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					UIHelper.ToastMessage(context, "操作成功");
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					UIHelper.ToastMessage(context, "操作失败");
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					UIHelper.ToastMessage(context, "操作失败");
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					UIHelper.ToastMessage(context, "操作失败");
					break;
				}
			}
		};

		remoteReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context _context, Intent _intent) {
				Bundle bundle = _intent.getExtras();
				Object[] pdus = (Object[]) bundle.get("pdus");

				if (pdus != null && pdus.length > 0) {
					SmsMessage[] messages = new SmsMessage[pdus.length];
					for (int i = 0; i < messages.length; i++) {
						byte[] pdu = (byte[]) pdus[i];
						messages[i] = SmsMessage .createFromPdu(pdu);
					}

					for (SmsMessage msg : messages) {
						String sender = msg.getOriginatingAddress();
						Log.e("xxxx", msg.getMessageBody());
						if (simNo.equals(sender)
								|| ("=861" + simNo).equals(sender)) {
							RemoteStateTxt.setText(msg.getMessageBody());
							this.abortBroadcast();
							break;
						}
					}
				}
			}
		};
	}

	private void iniData() {
		String SENT_SMS_ACTION = "SENT_SMS_ACTION";
		Intent sentIntent = new Intent(SENT_SMS_ACTION);
		sentPI = PendingIntent.getBroadcast(context, 0, sentIntent, 0);
		// 处理发送状态
		context.registerReceiver(sendReceiver,
				new IntentFilter(SENT_SMS_ACTION));

		String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
		// 处理接受状态
		Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
		deliverPI = PendingIntent.getBroadcast(context, 0, deliverIntent, 0);
		context.registerReceiver(getReceiver, new IntentFilter(
				DELIVERED_SMS_ACTION));

		IntentFilter smsIntent = new IntentFilter(
				"android.provider.Telephony.SMS_RECEIVED");
		smsIntent.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		context.registerReceiver(remoteReceiver, smsIntent);
	}

	public void ServerNumSureBtnClick(View v) {
		if (ServerNum.getText().toString().isEmpty()) {
			UIHelper.ToastMessage(this, "服务器号码不能为空");
		} else if (!ServerNum.getText().toString().isEmpty()
				&& !ServerNum.getText().toString().matches("[0-9+]*")) {
			UIHelper.ToastMessage(this, "服务器号码只能是数字和+");
		} else {
			sendSMS(CommandCode.SET_SERVER_NO + ServerNum.getText().toString());
		}
	}

	public void ServerNumSetBtnClick(View v) {
		sendSMS(CommandCode.SET_SERVER_NO_SELF);
	}

	public void AllClick(View v) {
		if (v.equals(AllOpenBtn)) {
			sendSMS(CommandCode.ALL_CONEECT);
		}
		if (v.equals(AllCloseBtn)) {
			sendSMS(CommandCode.ALL_CUT);
		}
	}

	public void RemoteNumSureBtnClick(View v) {

		if (RemoteNum.getText().toString().isEmpty()) {
			UIHelper.ToastMessage(this, "远程设备SN号不能为空");
		} else if (!RemoteNum.getText().toString().isEmpty()
				&& !RemoteNum.getText().toString().matches("[0-9a-zA-Z]*")) {
			UIHelper.ToastMessage(this, "远程设备SN号输入只能是数字和字母");
		} else {
			sendSMS(CommandCode.SET_ROMOTE_SN_NO
					+ ServerNum.getText().toString());
		}
	}

	public void RemoteStateSearchBtnClick(View v) {
		smsManager.sendTextMessage(simNo, null, CommandCode.CHECK_ROMOTE_STATE,
				null, null);
		// sendSMS(CommandCode.CHECK_ROMOTE_STATE);
	}

	private void sendSMS(String content) {

		smsManager.sendTextMessage(simNo, null, content, sentPI, deliverPI);
		UIHelper.ToastMessage(context, "指令发送中");
	}

	class CutListener implements OnTouchListener {

		public boolean onTouch(View v, MotionEvent event) {

			switch (v.getId()) {
			case R.id.Cut1Btn:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					sendSMS(CommandCode.CONNECT_ONE);
				}
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					sendSMS(CommandCode.CUT_ONE);
				}
				break;
			case R.id.Cut2Btn:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					sendSMS(CommandCode.CONNECT_TWO);
				}
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					sendSMS(CommandCode.CUT_TWO);
				}
				break;
			case R.id.Cut3Btn:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					sendSMS(CommandCode.CONNECT_THREE);
				}
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					sendSMS(CommandCode.CUT_THREE);
				}
				break;
			case R.id.Cut4Btn:
				if (event.getAction() == MotionEvent.ACTION_UP) {
					sendSMS(CommandCode.CONNECT_FOUR);
				}
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					sendSMS(CommandCode.CUT_FOUR);
				}
				break;
			}
			return false;
		}
	}

	private void unregisterReceiver() {
		context.unregisterReceiver(sendReceiver);
		context.unregisterReceiver(getReceiver);
		context.unregisterReceiver(remoteReceiver);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - now) > 2000) {
				now = System.currentTimeMillis();
				UIHelper.ToastMessage(context, "再按一次退出程序");

			} else {
				System.exit(0);
			}
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver();
		super.onDestroy();
	}
}